package
{
	import com.*;
	import com.Engine.*;
	import com.Packet.*;
	import com.UI.*;
	import com.adobe.serialization.json.JSON;
	
	import flash.display.*;
	import flash.events.*;
	import flash.external.*;
	import flash.filters.*;
	import flash.geom.*;
	import flash.net.*;
	import flash.system.*;
	import flash.system.LoaderContext;
	import flash.text.*;
	import flash.ui.*;
	import flash.utils.*;
	
	import org.aswing.*;
	import org.aswing.border.*;
	import org.aswing.border.EmptyBorder;
	import org.aswing.colorchooser.*;
	import org.aswing.ext.*;
	import org.aswing.geom.*;
	import org.aswing.plaf.*;
	import org.aswing.skinbuilder.SkinProgressBarBackground;
	import org.aswing.skinbuilder.SkinProgressBarForeground;
	import org.aswing.skinbuilder.SkinScrollBarBackground;
	import org.aswing.skinbuilder.SkinScrollBarThumb;
	import org.aswing.skinbuilder.SkinScrollBarUI;
	
	
	[SWF(width="1200",height="600",frameRate="24",backgroundColor="#000000")]
	public class Client extends Sprite implements IEventDispatcher
	{

		//static public var _AccountType:int = 0;
		private var _socket:Socket;
		private var _byteBuffer:ByteArray;
		private var _bRecvHead:Boolean = false;//0表示全部读完了，1表示长度读取完毕 2表示正在读取数据
		private var _nNeedRecvLength:int = 0;
		
		private var _loaderMutiple:LoaderMutiple;
		private var _listCSVData:Array = new Array;
		private var _listCSV:Array = new Array;
		private var _listSWFData:Array = new Array;
		private var _listSWF:Array = new Array;
		
		private static var _appDomainUI:ApplicationDomain;
		private static var _appDomainItem:ApplicationDomain;
		private static var _appDomainSkill:ApplicationDomain;
		private static var _appDomainEffect:ApplicationDomain;
		private static var _appDomainBuff:ApplicationDomain;
		
		//public var _panelChat:PanelChat;
		public var mainWindow:JWindow;
		private var _beConnecting:Boolean;
		
		private var _ip:String = "127.0.0.1";
		private var _port:uint = 8001;
		static public var _headOffsetYBoy:int = 0;//-15;
		static public var _headOffsetYGirl:int =0;// -22;
		
		public function Client()
		{
			if(_instance == null)
				_instance = this;
			super();

			_byteBuffer = new ByteArray();
			_byteBuffer.endian =  Endian.LITTLE_ENDIAN;
			//stage.quality=StageQuality.LOW;
			
			//_ip = "192.168.1.200";
			//_ip = "183.60.84.47";
			//_ip = "app100617823-1.qzoneapp.com";
			//Engine.httpServer = 'http://app100617823.qzoneapp.com/';
			//
			//flash.system.Security.allowDomain('*');
			_beConnecting = false;
			
			addEventListener("0", phPing_0);
			
			var param:Object = root.loaderInfo.parameters;
			if (param["open_id"] != null) 
			{
				Engine.open_id = param["open_id"];
			} 
			if (param["open_key"] != null) 
			{
				Engine.open_key = param["open_key"];
			} 
			if (param["gender"] != null) 
			{
				Engine.gender = param["gender"];
			} 
			if (param["nickname"] != null) 
			{
				Engine.nickname = param["nickname"];
			} 
			if (param["province"] != null) 
			{
				Engine.province = param["province"];
			} 
			if (param["city"] != null) 
			{
				Engine.city = param["city"];
			} 
			if (param["figureurl"] != null) 
			{
				Engine.figureurl = param["figureurl"];
			} 
			if (param["account_type"] != null) 
			{
				Engine.account_type = param["account_type"];
			} 

			/*if(Engine.open_id.length != 0 && Engine.open_key.length != 0)
			{
				_loader = new URLLoader();
				_loader.dataFormat = URLLoaderDataFormat.BINARY;
				var str:String = new String;
				str = Engine.httpServer+'get_user_info.php?openid='+Engine.open_id+'&openkey='+Engine.open_key;
				_loader.load(new URLRequest(str));
				_loader.addEventListener(IOErrorEvent.IO_ERROR,onUserInfoLoadedError);
				_loader.addEventListener(Event.COMPLETE,onUserInfoLoaded);
			}*/
			
			//http://app100617823.qzoneapp.com/get_user_info.php?openid=B624064BA065E01CB73F835017FE96FA&openkey=5F154D7D2751AEDC8527269006F290F70297B7E54667536C
			
			loadConfig();
		}
		protected var _loaderConfig:URLLoader;
		protected var _xmlConfig:XML;
		private function loadConfig():void
		{
			_loaderConfig = new URLLoader();
			_loaderConfig.dataFormat = URLLoaderDataFormat.BINARY;
			_loaderConfig.addEventListener(IOErrorEvent.IO_ERROR,onConfigLoadedError);
			_loaderConfig.addEventListener(Event.COMPLETE,onConfigLoaded);	
			_loaderConfig.load(new URLRequest(Engine.httpServer+"Client.xml"));
		}
		
		/**
		 * 解析配置文件
		 */ 
		protected function onConfigLoaded(e:Event):void
		{
			_loaderConfig.removeEventListener(Event.COMPLETE,onConfigLoaded);
			_loaderConfig.removeEventListener(IOErrorEvent.IO_ERROR,onConfigLoadedError);
			var by:ByteArray = _loaderConfig.data as ByteArray;
			if(by == null)
			{
				_loaderConfig.close();
				_loaderConfig = null;
				return;
			}
			var configXML:String = by.readUTFBytes(by.bytesAvailable);
			if(_xmlConfig != null)
			{
				_xmlConfig = null;
			}
			_xmlConfig = new XML(configXML);
			_ip = _xmlConfig.ip;
			_port = _xmlConfig.port;
			trace("_xmlConfig.ip:"+_xmlConfig.ip+",_xmlConfig.port:"+_xmlConfig.port);
			//Engine.W = _xmlConfig.sceneW;
			//Engine.H = _xmlConfig.sceneH;
			//map.tileWidth = _xmlConfig.tileX;
			//map.tileHeight = _xmlConfig.tileY;
			//map.mapWidth = _xmlConfig.mapW;
			//map.mapHeight = _xmlConfig.mapH;
			
			//map.load(_xmlConfig.id,_xmlConfig.hasTile,_xmlConfig.tileFormat); // 初始化地图
			_loaderConfig.close();
			_loaderConfig = null;
			//startup();
			
			loadSWF();
			
		}
		protected function onConfigLoadedError(e:IOErrorEvent):void
		{
			trace("load config io error");	
		}
		private var _loader:URLLoader = null;
		protected function onUserInfoLoadedError(e:IOErrorEvent):void
		{
			trace("onUserInfoLoadedError");	
		}
		
		/**
		 * 解析配置文件
		 */ 
		protected function onUserInfoLoaded(e:Event):void
		{
			_loader.removeEventListener(Event.COMPLETE,onUserInfoLoaded);
			_loader.removeEventListener(IOErrorEvent.IO_ERROR,onUserInfoLoadedError);
			//var by:ByteArray = _loader.data as ByteArray;
			//if(by == null)
			//	return;
			//by.uncompress();
			//var configXML:String = by.readUTFBytes(by.bytesAvailable);
			
			//_xmlConfig = new XML(configXML);
			
			var jsonArray:Object = com.adobe.serialization.json.JSON.decode(URLLoader(e.target).data);         //获取数组中存储的数据         
			//for (var i=0; i<jsonArray.length; i++) {        trace( jsonArray[i].type );
			if(jsonArray != null)
			{
				Engine.province = jsonArray.province;
				Engine.city = jsonArray.city;
				Engine.figureurl = jsonArray.figureurl;
			}
			initMainWindow();
			
			
		}
		
		private function loadSWF():void
		{
			_listSWF.push("swf/Item.swf");
			_listSWF.push("swf/Skill.swf");
			_listSWF.push("swf/Effect.swf");
			_listSWF.push("swf/UI.swf");
			_listSWF.push("swf/Buff.swf");
			
			_loaderMutiple = new LoaderMutiple();
			_loaderMutiple.addEventListener(Event.COMPLETE,onSWFLoaded);
			_loaderMutiple.loadAppDomain(_listSWFData,_listSWF);
			_loaderMutiple.x = (1200 - _loaderMutiple.width)/2;
			addChild(_loaderMutiple);	
		}
		
		private function onSWFLoaded(e:Event):void
		{
			
			var nIndex:uint = 0;
			_appDomainItem = _listSWFData[nIndex++] as ApplicationDomain;
			_appDomainSkill = _listSWFData[nIndex++] as ApplicationDomain;
			_appDomainEffect = _listSWFData[nIndex++] as ApplicationDomain;
			_appDomainUI = _listSWFData[nIndex++] as ApplicationDomain;
			_appDomainBuff = _listSWFData[nIndex++] as ApplicationDomain;
			
			var target:LoaderMutiple = e.target as LoaderMutiple;
			target.removeEventListener(Event.COMPLETE,onSWFLoaded);
			target.clear();
			Engine.ObjectDefaultImage = Client.getUIElement("img_default_image") as MovieClip;
			loadCSV();
		}
		
		private function loadCSV():void
		{
			_listCSV.push("csv/item.csv");
			_listCSV.push("csv/mall_ingot.csv");
			_listCSV.push("csv/mall_money.csv");
			_listCSV.push("csv/mall_honour.csv");
			_listCSV.push("csv/pet.csv");
			_listCSV.push("csv/skill.csv");
			_listCSV.push("csv/map.csv");
			_listCSV.push("csv/title.csv");
			_listCSV.push("csv/buff.csv");
			_listCSV.push("csv/home_building.csv");
			_listCSV.push("csv/home_cate.csv");
			_listCSV.push("csv/home_land.csv");
			_listCSV.push("csv/home_pet_egg.csv");
			_listCSV.push("csv/home_pet_book.csv");
			_listCSV.push("csv/task.csv");
			_listCSV.push("csv/copy.csv");
			_listCSV.push("csv/filter.csv");
			
			removeChild(_loaderMutiple);
			_loaderMutiple = null;
			_loaderMutiple = new LoaderMutiple();
			_loaderMutiple.addEventListener(Event.COMPLETE,onCSVLoaded);
			_loaderMutiple.loadText(_listCSVData,_listCSV,true);
			_loaderMutiple.x = (1200 - _loaderMutiple.width)/2;
			addChild(_loaderMutiple);
		}
		private static var _ItemCSV:Array = new Array();
		private function loadItemCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.icon_id = csv.data[i][nIndex++];
				
				obj.overlap_count = csv.data[i][nIndex++];
				
				obj.require_level = csv.data[i][nIndex++];
				obj.require_race = csv.data[i][nIndex++];
				obj.require_gender = csv.data[i][nIndex++];
				
				obj.atlas_material_0 = csv.data[i][nIndex++];
				obj.atlas_material_1 = csv.data[i][nIndex++];
				obj.atlas_material_2 = csv.data[i][nIndex++];
				obj.atlas_compose_equip = csv.data[i][nIndex++];
				
				obj.equip_type = csv.data[i][nIndex++];
				obj.equip_image_id = csv.data[i][nIndex++];
				
				obj.equip_hp_max = csv.data[i][nIndex++];
				obj.equip_hp_min = csv.data[i][nIndex++];
				obj.equip_ap_max = csv.data[i][nIndex++];
				obj.equip_ap_min = csv.data[i][nIndex++];
				
				obj.equip_dp_max = csv.data[i][nIndex++];
				obj.equip_dp_min = csv.data[i][nIndex++];
				
				obj.equip_sp_max = csv.data[i][nIndex++];
				obj.equip_sp_min = csv.data[i][nIndex++];
				
				obj.equip_enhanceHL_max = csv.data[i][nIndex++];
				obj.equip_enhanceHL_min = csv.data[i][nIndex++];
				obj.equip_enhanceBD_max = csv.data[i][nIndex++];
				obj.equip_enhanceBD_min = csv.data[i][nIndex++];
				obj.equip_enhanceHS_max = csv.data[i][nIndex++];
				obj.equip_enhanceHS_min = csv.data[i][nIndex++];
				
				obj.equip_resistHL_max = csv.data[i][nIndex++];
				obj.equip_resistHL_min = csv.data[i][nIndex++];
				obj.equip_resistBD_max = csv.data[i][nIndex++];
				obj.equip_resistBD_min = csv.data[i][nIndex++];
				obj.equip_resistHS_max = csv.data[i][nIndex++];
				obj.equip_resistHS_min = csv.data[i][nIndex++];
				
				obj.equip_prop_BJ_max = csv.data[i][nIndex++];
				obj.equip_prop_BJ_min = csv.data[i][nIndex++];
				obj.equip_prop_SB_max = csv.data[i][nIndex++];
				obj.equip_prop_SB_min = csv.data[i][nIndex++];
				obj.equip_prop_FJ_max = csv.data[i][nIndex++];
				obj.equip_prop_FJ_min = csv.data[i][nIndex++];
				obj.equip_prop_LJ_max = csv.data[i][nIndex++];
				obj.equip_prop_LJ_min = csv.data[i][nIndex++];
				
				_ItemCSV[obj.id] = obj;
				
			}
		}
		public function GetItemCSV(csv_id:uint):Object
		{
			return _ItemCSV[csv_id];
		}
		
		private static var _SkillCSV:Array = new Array();
		private function loadSkillCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.kind = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.icon_id = csv.data[i][nIndex++];
				
				obj.require_level = csv.data[i][nIndex++];
				obj.require_gender = csv.data[i][nIndex++];
				
				
				obj.action_self = csv.data[i][nIndex++];
				obj.action_target = csv.data[i][nIndex++];
				obj.effect_self = csv.data[i][nIndex++];
				
				obj.effect_self_fullscreen = csv.data[i][nIndex++];
				obj.effect_target_attacked = csv.data[i][nIndex++];
				obj.effect_target_hit = csv.data[i][nIndex++];
				
				
				_SkillCSV[obj.id] = obj;
				
			}
		}
		public function GetSkillCSV(csv_id:uint):Object
		{
			return _SkillCSV[csv_id];
		}
		public static var _MallIngotCSV:Array = new Array();
		private function loadMallIngotCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.item_id = csv.data[i][nIndex++];
				obj.price = csv.data[i][nIndex++];
				
				_MallIngotCSV[obj.csv_id] = obj;
				
			}
		}
		
		public static var _MallMoneyCSV:Array = new Array();
		private function loadMallMoneyCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.item_id = csv.data[i][nIndex++];
				obj.price = csv.data[i][nIndex++];
				
				_MallMoneyCSV[obj.csv_id] = obj;
				
			}
		}
		
		public static var _MallHonourCSV:Array = new Array();
		private function loadMallHonourCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.item_id = csv.data[i][nIndex++];
				obj.price = csv.data[i][nIndex++];
				
				_MallHonourCSV[obj.csv_id] = obj;
				
			}
		}
		
		//public function GetMallCSV(csv_id:uint):Object
		//{
		//	return _MallCSV[csv_id];
		//}
		
		public static var _PetCSV:Array = new Array();
		private function loadPetCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.image_id = csv.data[i][nIndex++];
				
				obj.level = csv.data[i][nIndex++];
				obj.gender = csv.data[i][nIndex++];
				obj.require_level = csv.data[i][nIndex++];
				obj.require_gender = csv.data[i][nIndex++];
				obj.growth_max = csv.data[i][nIndex++];
				
				obj.growth_min = csv.data[i][nIndex++];
				obj.resistHY_max = csv.data[i][nIndex++];
				obj.resistHY_min = csv.data[i][nIndex++];
				obj.resistZS_max = csv.data[i][nIndex++];
				obj.resistZS_min = csv.data[i][nIndex++];
				obj.resistFD_max = csv.data[i][nIndex++];
				obj.resistFD_min = csv.data[i][nIndex++];
				obj.resistGH_max = csv.data[i][nIndex++];
				obj.resistGH_min = csv.data[i][nIndex++];
				
				obj.resistJD_max = csv.data[i][nIndex++];
				obj.resistJD_min = csv.data[i][nIndex++];
				
				obj.skill_0 = csv.data[i][nIndex++];
				obj.has_skill_odds_0 = csv.data[i][nIndex++];
				obj.skill_1 = csv.data[i][nIndex++];
				obj.has_skill_odds_1 = csv.data[i][nIndex++];
				obj.skill_2 = csv.data[i][nIndex++];
				obj.has_skill_odds_2 = csv.data[i][nIndex++];
				obj.skill_3 = csv.data[i][nIndex++];
				obj.has_skill_odds_3 = csv.data[i][nIndex++];
				
				_PetCSV[obj.csv_id] = obj;
				
			}
		}
		
		public function GetPetCSV(csv_id:uint):Object
		{
			return _PetCSV[csv_id];
		}
		
		public static var _MapCSV:Array = new Array();
		private function loadMapCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.parent_map_id = csv.data[i][nIndex++];
				obj.require_level = csv.data[i][nIndex++];
				obj.require_item_id = csv.data[i][nIndex++];
				obj.monster_level_min = csv.data[i][nIndex++];
				obj.monster_level_max = csv.data[i][nIndex++];
				obj.base_x = csv.data[i][nIndex++];
				obj.base_y = csv.data[i][nIndex++];

				
				_MapCSV[obj.csv_id] = obj;
				
			}
		}
		
		
		
		public function GetMapCSV(csv_id:uint):Object
		{
			return _MapCSV[csv_id];
		}
		public function GetTitleCSV(csv_id:uint):Object
		{
			return _TitleCSV[csv_id];
		}
		
		public static var _TitleCSV:Array = new Array();
		private function loadTitleCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.level = csv.data[i][nIndex++];
				obj.force_show = csv.data[i][nIndex++];
				
				_TitleCSV[obj.csv_id] = obj;
				
			}
		}
		
		public function GetBuffCSV(csv_id:uint):Object
		{
			return _BuffCSV[csv_id];
		}
		
		public static var _BuffCSV:Array = new Array();
		private function loadBuffCSV(csv:CSV):void
		{
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.icon_id = csv.data[i][nIndex++];
				
				_BuffCSV[obj.csv_id] = obj;
			}
		}
		
		public function GetHomeBuildingCSV(csv_id:uint):Object
		{
			return _HomeBuildingCSV[csv_id];
		}
		
		public static var _HomeBuildingCSV:Array = new Array();
		private function loadHomeBuildingCSV(csv:CSV):void
		{
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.image_id = csv.data[i][nIndex++];
				obj.require_level = csv.data[i][nIndex++];
				obj.bustling = csv.data[i][nIndex++];
				
				_HomeBuildingCSV[obj.csv_id] = obj;
			}
		}
		
		public function GetHomeCateCSV(csv_id:uint):Object
		{
			return _HomeCateCSV[csv_id];
		}
		
		public static var _HomeCateCSV:Array = new Array();
		private function loadHomeCateCSV(csv:CSV):void
		{
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.item_id = csv.data[i][nIndex++];
				obj.require_level = csv.data[i][nIndex++];
				
				_HomeCateCSV[obj.csv_id] = obj;
			}
		}
		
		public function GetHomeLandCSV(csv_id:uint):Object{return _HomeLandCSV[csv_id];}
		public static var _HomeLandCSV:Array = new Array();
		private function loadHomeLandCSV(csv:CSV):void
		{
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.item_id = csv.data[i][nIndex++];
				obj.require_level = csv.data[i][nIndex++];
				
				_HomeLandCSV[obj.csv_id] = obj;
			}
		}
		
		public function GetHomePetEggCSV(csv_id:uint):Object{return _HomePetEggCSV[csv_id];}
		public static var _HomePetEggCSV:Array = new Array();
		private function loadHomePetEggCSV(csv:CSV):void
		{
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.item_id = csv.data[i][nIndex++];
				obj.require_level = csv.data[i][nIndex++];
				obj.price_min = csv.data[i][nIndex++];
				obj.price_max = csv.data[i][nIndex++];
				
				_HomePetEggCSV[obj.csv_id] = obj;
			}
		}
		
		public function GetHomePetBookCSV(csv_id:uint):Object{return _HomePetBookCSV[csv_id];}
		public static var _HomePetBookCSV:Array = new Array();
		private function loadHomePetBookCSV(csv:CSV):void
		{
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.item_id = csv.data[i][nIndex++];
				obj.require_level = csv.data[i][nIndex++];
				obj.price_min = csv.data[i][nIndex++];
				obj.price_max = csv.data[i][nIndex++];
				
				_HomePetBookCSV[obj.csv_id] = obj;
			}
		}
		public function GetTaskCSV(csv_id:uint):Object{return _TaskCSV[csv_id];}
		public static var _TaskCSV:Array = new Array();
		private function loadTaskCSV(csv:CSV):void
		{
			
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.task_id = obj.csv_id;
				obj.type = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.count_everyday = csv.data[i][nIndex++];
				obj.time_limit = csv.data[i][nIndex++];
				obj.enable_record = csv.data[i][nIndex++];
				obj.enable_double = csv.data[i][nIndex++];
				obj.require_complete_task_id = csv.data[i][nIndex++];
				obj.require_level = csv.data[i][nIndex++];
				obj.accepte_map_id = csv.data[i][nIndex++];
				obj.accepte_npc_id = csv.data[i][nIndex++];
				obj.complete_map_id = csv.data[i][nIndex++];
				obj.complete_npc_id = csv.data[i][nIndex++];
				obj.reward_wood = csv.data[i][nIndex++];
				obj.reward_food = csv.data[i][nIndex++];
				obj.reward_exp = csv.data[i][nIndex++];
				obj.reward_money = csv.data[i][nIndex++];
				obj.reward_items = csv.data[i][nIndex++];
				
				_TaskCSV[obj.csv_id] = obj;
				
			}
		}
		
		public function GetCopyCSV(csv_id:uint):Object{return _CopyCSV[csv_id];}
		public static var _CopyCSV:Array = new Array();
		private function loadCopyCSV(csv:CSV):void
		{
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.type = csv.data[i][nIndex++];
				obj.task_id = csv.data[i][nIndex++];
				obj.image_id = csv.data[i][nIndex++];
				obj.name = csv.data[i][nIndex++];
				obj.description = csv.data[i][nIndex++];
				obj.reward_items = csv.data[i][nIndex++];
				
				_CopyCSV[obj.csv_id] = obj;
				
			}
		}
		
		public function GetFilterCSV(csv_id:uint):Object{return _FilterCSV[csv_id];}
		public static var _FilterCSV:Array = new Array();
		private function loadFilterCSV(csv:CSV):void
		{
			for(var i:uint = 0; i < csv.data.length; i++)
			{
				var obj:Object = new Object();
				var nIndex:uint = 0;
				
				obj.csv_id = csv.data[i][nIndex++];
				obj.word = csv.data[i][nIndex++];
				
				_FilterCSV[obj.csv_id] = obj;
				
			}
		}
		public static function wordFilter(str:String):String
		{
			var bLegal:Boolean = true;
			for each(var obj:Object in _FilterCSV)
			{
				//var nIndex:int = str.indexOf(obj.word);
				//if(nIndex != -1)
				//{
					var strReplace:String = "";
					for(var i:int = 0; i < (obj.word as String).length; i++)
					{
						strReplace += '*';
					}
					//str.replace((obj.word as String),strReplace);
					//bLegal = false;
				//}
				var nIndex:int = str.indexOf(obj.word);
				while(nIndex != -1)
				{
					str = str.substr(0,nIndex) + strReplace + str.substr(nIndex+(obj.word as String).length,str.length);
					bLegal = false;
					nIndex = str.indexOf(obj.word);
				}
			}
			return str;
		}
		
		private function onCSVLoaded(e:Event):void
		{
			
			var nIndex:uint = 0;
			
			var csv:CSV = new CSV;
			csv.data = _listCSVData[0];
			csv.decode();
			loadItemCSV(csv);
			
			csv.data = _listCSVData[1];
			csv.decode();
			loadMallIngotCSV(csv);
			
			csv.data = _listCSVData[2];
			csv.decode();
			loadMallMoneyCSV(csv);
			
			csv.data = _listCSVData[3];
			csv.decode();
			loadMallHonourCSV(csv);
			
			csv.data = _listCSVData[4];
			csv.decode();
			loadPetCSV(csv);
			
			csv.data = _listCSVData[5];
			csv.decode();
			loadSkillCSV(csv);
			
			csv.data = _listCSVData[6];
			csv.decode();
			loadMapCSV(csv);
			
			csv.data = _listCSVData[7];
			csv.decode();
			loadTitleCSV(csv);
			
			csv.data = _listCSVData[8];
			csv.decode();
			loadBuffCSV(csv);
			
			csv.data = _listCSVData[9];
			csv.decode();
			loadHomeBuildingCSV(csv);
			
			csv.data = _listCSVData[10];
			csv.decode();
			loadHomeCateCSV(csv);
			
			csv.data = _listCSVData[11];
			csv.decode();
			loadHomeLandCSV(csv);
			
			csv.data = _listCSVData[12];
			csv.decode();
			loadHomePetEggCSV(csv);
			
			csv.data = _listCSVData[13];
			csv.decode();
			loadHomePetBookCSV(csv);
			
			csv.data = _listCSVData[14];
			csv.decode();
			loadTaskCSV(csv);
			
			csv.data = _listCSVData[15];
			csv.decode();
			loadCopyCSV(csv);
			
			csv.data = _listCSVData[16];
			csv.decode();
			loadFilterCSV(csv);
			
			
			var target:LoaderMutiple = e.target as LoaderMutiple;
			target.removeEventListener(Event.COMPLETE,onCSVLoaded);
			target.clear();
			
			if(Engine.open_id.length != 0 && Engine.open_key.length != 0)
			{
				_loader = new URLLoader();
				_loader.dataFormat = URLLoaderDataFormat.BINARY;
				var str:String = new String;
				str = Engine.httpServer+'get_user_info.php?openid='+Engine.open_id+'&openkey='+Engine.open_key;
				_loader.load(new URLRequest(str));
				_loader.addEventListener(IOErrorEvent.IO_ERROR,onUserInfoLoadedError);
				_loader.addEventListener(Event.COMPLETE,onUserInfoLoaded);
			}
			else
			{
				initMainWindow();
			}
		}
		
		public static function getUIBitmapData(_name:String):BitmapData
		{
			return Engine.getElement(_appDomainUI,_name,true) as BitmapData;
		}
		
		public static function getUIElement(_name:String):*
		{
			var tmp:* = Engine.getElement(_appDomainUI,_name);
			if(tmp == null)
				trace("getUIElement: "+_name +" is null!!!");
			return tmp;
		}
		
		public static function getItemElement(_name:String):*
		{
			return Engine.getElement(_appDomainItem,_name);
		}
		
		public static function getSkillElement(_name:String):*
		{
			return Engine.getElement(_appDomainSkill,_name);
		}
		
		public static function getEffectElement(_name:String):*
		{
			return Engine.getElement(_appDomainEffect,_name);
		}
		
		public static function getBuffElement(_name:String):*
		{
			return Engine.getElement(_appDomainBuff,_name);
		}
		
		public static function getUIBitmap(_name:String):Bitmap
		{
			return Engine.getElement(_appDomainUI,_name) as Bitmap;
		}
		
		public function get socket():Socket
		{
			return _socket;
		}
		public function get beConnected():Boolean
		{
			return _socket!= null && _socket.connected;
		}
		public function get beConnecting():Boolean
		{
			return _beConnecting;
		}

		private static var _instance:* = null;
		public static function getInstance():Client
		{
			if(_instance == null)
				_instance = new Client();
			return _instance;
		}
		private function initDefaultUI():void
		{
			/*var uiDefaults:Array = [ 
				"ScrollBarUI", SkinScrollBarUI, 
			];
			UIManager.getDefaults().putDefaults(uiDefaults);
			
			var comDefaults:Array = [
				"ScrollBar.opaque", false, 
				"ScrollBar.thumbDecorator", SkinScrollBarThumb, 
				"ScrollBar.fg", SkinScrollBarBackground,
				"ScrollBar.verticalBGImage", Client.getUIElement("ScrollBar_verticalBGImage") as DisplayObject, 
				"ScrollBar.horizotalBGImage", Client.getUIElement("ScrollBar_horizotalBGImage") as DisplayObject,
				"ScrollBar.verticalBGDisabledImage", Client.getUIElement("ScrollBar_verticalBGImage") as DisplayObject, 
				"ScrollBar.horizotalBGDisabledImage", Client.getUIElement("ScrollBar_horizotalBGImage") as DisplayObject,
				
				"ScrollBar.arrowLeft.defaultImage", Client.getUIElement("ScrollBar_arrowLeft_defaultImage") as DisplayObject,
				"ScrollBar.arrowLeft.pressedImage", Client.getUIElement("ScrollBar_arrowLeft_pressedImage") as DisplayObject, 
				"ScrollBar.arrowLeft.disabledImage", Client.getUIElement("ScrollBar_arrowLeft_disabledImage") as DisplayObject, 
				"ScrollBar.arrowLeft.rolloverImage", Client.getUIElement("ScrollBar_arrowLeft_rolloverImage") as DisplayObject, 
				
				"ScrollBar.arrowRight.defaultImage", Client.getUIElement("ScrollBar_arrowRight_defaultImage") as DisplayObject, 
				"ScrollBar.arrowRight.pressedImage", Client.getUIElement("ScrollBar_arrowRight_pressedImage") as DisplayObject,
				"ScrollBar.arrowRight.disabledImage", Client.getUIElement("ScrollBar_arrowRight_disabledImage") as DisplayObject,
				"ScrollBar.arrowRight.rolloverImage", Client.getUIElement("ScrollBar_arrowRight_rolloverImage") as DisplayObject,
				
				"ScrollBar.arrowUp.defaultImage", Client.getUIElement("ScrollBar_arrowUp_defaultImage") as DisplayObject,
				"ScrollBar.arrowUp.pressedImage", Client.getUIElement("ScrollBar_arrowUp_pressedImage") as DisplayObject,
				"ScrollBar.arrowUp.disabledImage", Client.getUIElement("ScrollBar_arrowUp_disabledImage") as DisplayObject,
				"ScrollBar.arrowUp.rolloverImage", Client.getUIElement("ScrollBar_arrowUp_rolloverImage") as DisplayObject,
				
				"ScrollBar.arrowDown.defaultImage", Client.getUIElement("ScrollBar_arrowDown_defaultImage") as DisplayObject,
				"ScrollBar.arrowDown.pressedImage", Client.getUIElement("ScrollBar_arrowDown_pressedImage") as DisplayObject,
				"ScrollBar.arrowDown.disabledImage", Client.getUIElement("ScrollBar_arrowDown_disabledImage") as DisplayObject,
				"ScrollBar.arrowDown.rolloverImage", Client.getUIElement("ScrollBar_arrowDown_rolloverImage") as DisplayObject,
				
				"ScrollBar.thumbVertical.defaultImage", Client.getUIElement("ScrollBar_thumbVertical_defaultImage") as DisplayObject,
				"ScrollBar.thumbVertical.pressedImage", Client.getUIElement("ScrollBar_thumbVertical_pressedImage") as DisplayObject,
				"ScrollBar.thumbVertical.disabledImage", Client.getUIElement("ScrollBar_thumbVertical_disabledImage") as DisplayObject,
				"ScrollBar.thumbVertical.rolloverImage", Client.getUIElement("ScrollBar_thumbVertical_rolloverImage") as DisplayObject, 
				"ScrollBar.thumbVertical.iconImage", Client.getUIElement("ScrollBar_thumbVertical_iconImage") as DisplayObject,
				"ScrollBar.thumbVertical.iconPressedImage", Client.getUIElement("ScrollBar_thumbVertical_iconPressedImage") as DisplayObject,
				"ScrollBar.thumbVertical.iconDisabledImage", Client.getUIElement("ScrollBar_thumbVertical_iconDisabledImage") as DisplayObject,
				"ScrollBar.thumbVertical.iconRolloverImage", Client.getUIElement("ScrollBar_thumbVertical_iconRolloverImage") as DisplayObject,
				
				"ScrollBar.thumbHorizontal.defaultImage", Client.getUIElement("ScrollBar_thumbHorizontal_defaultImage") as DisplayObject,
				"ScrollBar.thumbHorizontal.pressedImage", Client.getUIElement("ScrollBar_thumbHorizontal_pressedImage") as DisplayObject, 
				"ScrollBar.thumbHorizontal.disabledImage", Client.getUIElement("ScrollBar_thumbHorizontal_disabledImage") as DisplayObject, 
				"ScrollBar.thumbHorizontal.rolloverImage", Client.getUIElement("ScrollBar_thumbHorizontal_rolloverImage") as DisplayObject, 
				"ScrollBar.thumbHorizontal.iconImage", Client.getUIElement("ScrollBar_thumbHorizontal_iconImage") as DisplayObject,
				"ScrollBar.thumbHorizontal.iconPressedImage", Client.getUIElement("ScrollBar_thumbHorizontal_iconPressedImage") as DisplayObject, 
				"ScrollBar.thumbHorizontal.iconDisabledImage", Client.getUIElement("ScrollBar_thumbHorizontal_iconDisabledImage") as DisplayObject, 
				"ScrollBar.thumbHorizontal.iconRolloverImage", Client.getUIElement("ScrollBar_thumbHorizontal_iconRolloverImage") as DisplayObject]
			
			UIManager.getDefaults().putDefaults(comDefaults);*/
		}
		private function initMainWindow():void
		{
			AsWingManager.initAsStandard(this);
			//System.useCodePage=true;
			
			initDefaultUI();
			
			
			mainWindow = new JWindow();
			//_panelChat = new PanelChat();
			//_panelMain = new PanelMain(this);
			//addChild(PanelMain.getInstance())
			
			// 得到窗口容器
			var pane:Container = mainWindow.getContentPane();
			pane.setLayout(new EmptyLayout());
			
			mainWindow.setSizeWH(1200,600);
			//mainWindow.x = (1200 - mainWindow.width)/2;
			//mainWindow.x = (1200 - mainWindow.width)/2;
			//mainWindow.y = (600 - mainWindow.height)/2;
			
			PanelMain.getInstance().setLocation(new IntPoint(0, 0));
			PanelMain.getInstance().setSize(new IntDimension(1200, 600));
			PanelMain.getInstance().setPreferredSize(new IntDimension(1200, 600));
			
			//PanelChat.getInstance().setLocation(new IntPoint(800, 0));
			//PanelChat.getInstance().setSize(new IntDimension(200, 600));
			//PanelChat.getInstance().setPreferredSize(new IntDimension(200, 600));
			
			pane.append(PanelMain.getInstance());
			//pane.append(PanelChat.getInstance());
			
			//_panelChat.setOpaque(true);
			//PanelMain.getInstance().setOpaque(true);
			//_mainWindow.setForegroundDecorator(
			//var img_background:DisplayObject = Client.getUIElement("img_main_background") as DisplayObject
			//_mainWindow.setForegroundDecorator(new AssetBackground(img_background));
			//PanelMain.getInstance().setBorder(new LineBorder(null,ASColor.HALO_BLUE,1,0));
			//_panelChat.setBorder(new LineBorder(null,ASColor.HALO_BLUE,1,0));
			//_mainWindow.setBorder(new LineBorder(null,ASColor.HALO_BLUE,1,0));
			
			mainWindow.show();
			FrameLogin.show();
		
			//CursorManager.getManager().setCursor(mainWindow,Client.getUIElement("img_cursor") as DisplayObject);
		}
		

		private function phPing_0(e:PacketEvent):void
		{
			sendPacketLogic(0);
		}
		
		public function connect():void
		{
			try
			{
				if(_socket != null && _socket.connected)
					return;
				if(_beConnecting)
					return;
				_socket = new Socket();
				//连接c++的时候需要反转下顺序
				_socket.endian = Endian.LITTLE_ENDIAN;
				
				_socket.addEventListener(Event.CONNECT, handleSocketConnect);
				_socket.addEventListener(Event.CLOSE, handleSocketClose);
				_socket.addEventListener(ProgressEvent.SOCKET_DATA, handleSocketData);
				_socket.addEventListener(IOErrorEvent.IO_ERROR, handleSocketIOError);
				_socket.addEventListener(IOErrorEvent.NETWORK_ERROR, handleSocketIOError);
				_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSocketSecurityError);
				
				_socket.connect(_ip, _port);
				_beConnecting = true;
				trace("Client.connect().");
			}
			catch(e:Error)
			{
				trace("connect:",e.getStackTrace()); 	 
			}
				
		}
		public function disconnect():void
		{
			try
			{
				
				if(_socket == null)
					return;
				_socket.removeEventListener(Event.CONNECT, handleSocketConnect);
				_socket.removeEventListener(Event.CLOSE, handleSocketClose);
				_socket.removeEventListener(ProgressEvent.SOCKET_DATA, handleSocketData);
				_socket.removeEventListener(IOErrorEvent.IO_ERROR, handleSocketIOError);
				_socket.removeEventListener(IOErrorEvent.NETWORK_ERROR, handleSocketIOError);
				_socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSocketSecurityError);
				_socket.close();
				_socket = null;
				_beConnecting = false;
			}
			catch(e:Error)
			{
				trace("disconnect:",e.getStackTrace()); 	 
			}
			
		}
		public function sendPacket(packet:Packet):void
		{
			var byteArray:ByteArray = Packet.encode(packet);
			byteArray.endian = Endian.LITTLE_ENDIAN;
			//writeToSocket(byteArray);
			try
			{
				_socket.writeInt(byteArray.length);
				_socket.writeBytes(byteArray);
				_socket.flush();
			}
			catch(e:Error)
			{
				//trace("socket没有连接"); 	 
				trace("sendPacket:",e.getStackTrace()); 
				//JOptionPane.showMessageDialog("","与服务器连接发生错误!");
				FrameLogin.show();
				disconnect();
			}
		}
		
		public function send(data:String):void
		{
			//writeToSocket(byteArray);
			try
			{
				//_socket.writeInt(byteArray.length);
				_socket.writeUTF(data);
				_socket.flush();
			}
			catch(e:Error)
			{
				//trace("socket没有连接"); 	 
				trace("sendPacket:",e.getStackTrace()); 
				//JOptionPane.showMessageDialog("","与服务器连接发生错误!");
				FrameLogin.show();
				disconnect();
			}
		}

		public function sendPacketLogic(action:int, msg:Array = null):void
		{
			sendPacket(new Packet(Packet.LOGIC,action,msg));  
		}
		
		
		private function handleSocketData(e:ProgressEvent):void
		{
			if(_socket == null)
				return;
			var bytes:int = _socket.bytesAvailable;
			while (bytes)
			{
				if(_socket == null)
					return;
				if (!_bRecvHead)
				{
					if(bytes < 4)
						break;
					_nNeedRecvLength = _socket.readInt();
					_bRecvHead = true;
					bytes = _socket.bytesAvailable;
				}
				else
				{
					//如果长度不够
					if(bytes < _nNeedRecvLength)
					{
						_socket.readBytes(_byteBuffer,_byteBuffer.bytesAvailable, 0);
						_nNeedRecvLength = _nNeedRecvLength - bytes;
						bytes = _socket.bytesAvailable;
					}
					else 
					{
						_socket.readBytes(_byteBuffer,_byteBuffer.bytesAvailable, _nNeedRecvLength);
						bytes = _socket.bytesAvailable;
						_bRecvHead = false;
						
						handlePacket(_byteBuffer);
					}
				}
			}
		}
		//消息类型     消息编号     消息主体
		
		private function handlePacket(byte:ByteArray):void
		{
			var msg:Array = Packet.decode(byte);
			var packet:Packet = new Packet(msg.shift(), msg.shift(), msg);
			_byteBuffer = new ByteArray();
			_byteBuffer.endian =  Endian.LITTLE_ENDIAN;
			dispatchEvent(new PacketEvent(String(packet.id), packet.body));
		}
		
		private function handleSocketConnect(e:Event):void
		{
			trace("~连接成功");
			/*var str:String = 'GET/HTTP/1.1\r\nHost:app100617823-1.qzoneapp.com:8001\r\n\r\n';
			try
			{
				//_socket.writeInt(byteArray.length);
				_socket.writeUTF(str);
				_socket.writeInt(1);
				_socket.writeInt(0);
				_socket.flush();
			}
			catch(e:Error)
			{
				//trace("socket没有连接"); 	 
				trace("sendPacket:",e.getStackTrace()); 
				//JOptionPane.showMessageDialog("","与服务器连接发生错误!");
				PanelMain.getInstance().showFrameLogin();
				disconnect();
			}*/
			_beConnecting = false;
		}
		
		private function handleSocketClose(e:Event):void
		{
			FrameInfo.showMessageDialog("","与服务器连接已经断开!");
			trace("连接关闭");
			_beConnecting = false;
			if(PanelMainHelp.getInstance().contains(SceneMain.getInstance()))
				PanelMainHelp.getInstance().removeChild(SceneMain.getInstance());
			if(PanelMain.getInstance().isInBattle)
				PanelMain.getInstance().leaveBattle();
			if(PanelMainHelp.getInstance().contains(SceneBattle.getInstance()))
				PanelMainHelp.getInstance().removeChild(SceneBattle.getInstance());
			CharInfo.clear();
			SceneMain.getInstance().clearup();
			FrameLogin.show();
			disconnect();
		}
		
		private function handleSocketIOError(e:IOErrorEvent):void
		{
			FrameInfo.showMessageDialog("","与服务器连接发生错误!");
			trace("连接出错");
			_beConnecting = false;
			FrameLogin.show();
			disconnect();
		}
		
		private function handleSocketSecurityError(e:SecurityErrorEvent):void
		{
			_beConnecting = false;
			disconnect();
			//FrameInfo.showMessageDialog("","与服务器连接认证失败!");
			//JOptionPane.showMessageDialog("","连接服务器失败!");
			//trace("handleSecurityError");
		}
	}
}